package com.heima.user.serviice.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.serviice.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author trk
 */
@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 用户登录
     *
     * @param loginDto 用户传递的手机号和密码
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {

        //1.有账号用户登录
            //1.1查询用户名密码是否为空
        if(StringUtils.isNotEmpty(loginDto.getPhone()) && StringUtils.isNotEmpty(loginDto.getPassword())){
            //1.2通过用户名查询用户数据
            //LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<ApUser>;
            //queryWrapper.eq(ApUser::getPhone,loginDto.getPassword());
            ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone , loginDto.getPhone()));
            //1.3用户不存在则返回1002
            if (user == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //1.4用户存在,获取salt,与密码向结合用MD5 加密
            String salt = user.getSalt();
            String asHex = DigestUtils.md5DigestAsHex((loginDto.getPassword() + salt).getBytes(Charset.forName("UTF-8")));
            //1.5对比两个密文 正确返回token 错误返回密码错误提示
            if (asHex.equals(user.getPassword())) {
                String token = AppJwtUtil.getToken((long) user.getId());
                user.setPassword("");
                user.setSalt("");

                Map<String,Object> map =new HashMap<>();
                map.put("user",user);
                map.put("token",token);

                return ResponseResult.okResult(map);
            }else {
               return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            //2.游客登录
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> map =new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
